package com.ys.controller.api.hr;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.YsCol;
import com.ys.service.business.ThrOperateCompanyBrandService;
import com.ys.service.business.ThrOperateCompanyEuropeTradeService;
import com.ys.service.business.ThrOperateCompanyVpsService;
import com.ys.service.hr.ThrOperateCompanyApplyService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/thrOperateCompanyApply")
public class ApiInterThrOperateCompanyApplyController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterThrOperateCompanyApplyController.class);
	
	@Autowired
	private CommonApiService<ThrOperateCompanyApply> commonApiService;
	@Autowired
	private ThrOperateCompanyApplyService thrOperateCompanyApplyService;

	@Autowired
	private ThrOperateCompanyVpsService thrOperateCompanyVpsService;

	@Autowired
	private ThrOperateCompanyBrandService thrOperateCompanyBrandService;

	@Autowired
	private ThrOperateCompanyEuropeTradeService thrOperateCompanyEuropeTradeService;
	

//	@RequiresPermissions("tpFbaPlanOrder:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute ThrOperateCompanyApply cond){
		
		commonApiService.dataAuth(MenuId.THR_OperateCompanyApply, cond);

		cond.addLeftJoin("TS_UserChange B on B.Id = A.OperatorChangeId")
				.addField("B.UserId operatorUserId")//运营人工号
				.addField("B.UserName operatorUserName")//运营人
				.addField("B.RoleName roleName")//运营人岗位
				.addField("B.DeptName deptName");//运营人部门

		cond.addLeftJoin("TS_OperateOrg O on O.Id = A.OperateOrgId")
				.addField("O.Name orgName");//机构名称
		cond.setOrderby("A.Vgsbm desc");

		return commonApiService.searchLay(cond);
	}

	/**
	 * 运营公司弹出框调用
	 */
//	@RequiresPermissions("tpFbaPlanOrder:view")
	@RequestMapping("/searchForModal")
    @ResponseBody
	public LayuiTableVoJA searchForModal(@ModelAttribute ThrOperateCompanyApply cond){
		
		commonApiService.dataAuth(MenuId.THR_OperateCompanyApply, cond);
		
		cond.addField("(A.Vgsbm + '/' + A.Vgsjc) AS nameLinked");
		
		cond.addLeftJoin("TS_UserInfo B on B.UserId = A.CUser")
			.addLeftJoin("YS_Role C on C.Id = B.RoleId")
			.addField("C.Name operatorRoleName");
		
		cond.addLeftJoin("TS_UserChange D on D.Id = A.OperatorChangeId")
			.addField("D.UserId operatorUserId")
			.addField("D.UserName operatorUserName")
			.addField("D.DeptId operatorDeptId");
		/*
		cond.addField("CASE " +
				"WHEN A.OperationsAttribute=2 THEN '运营账户' " +
				" ELSE '非运营账户' END operationsAttributetxt");//运营属性

		 */
		cond.addLeftJoin("TB_StaticConfig SC ON SC.Lev=A.OperationsAttribute AND SC.KeyTwo = 'OperateCompanyApply-OperationsAttribute' ")
				.addField("SC.Name operationsAttributetxt");//运营属性


		cond.where("A.OperationsStatus IN (2,3)");
		
		cond.setOrderby("A.Vgsbm asc");
		return commonApiService.searchLay(cond);
	}


	/**
	 * 运营公司信息弹出框调用
	 */
//	@RequiresPermissions("tpFbaPlanOrder:view")
	@RequestMapping("/searchForModal1")
	@ResponseBody
	public LayuiTableVoJA searchForModal1(@ModelAttribute ThrOperateCompanyApply cond){

		commonApiService.dataAuth(MenuId.THR_OperateCompanyApply, cond);

		cond.addField("(A.Vgsbm + '/' + A.Vgsjc) AS nameLinked");

		cond.addLeftJoin("TS_UserInfo B on B.UserId = A.CUser")
				.addLeftJoin("YS_Role C on C.Id = B.RoleId")
				.addField("C.Name operatorRoleName");

		cond.addLeftJoin("TS_UserChange D on D.Id = A.OperatorChangeId")
				.addField("D.UserId operatorUserId")
				.addField("D.UserName operatorUserName")
				.addField("D.DeptId operatorDeptId");
		/*
		cond.addField("CASE " +
				"WHEN A.OperationsAttribute=2 THEN '运营账户' " +
				" ELSE '非运营账户' END operationsAttributetxt");//运营属性
		 */
		cond.addLeftJoin("TB_StaticConfig SC ON SC.Lev=A.OperationsAttribute AND SC.KeyTwo = 'OperateCompanyApply-OperationsAttribute' ")
				.addField("SC.Name operationsAttributetxt");//运营属性


		cond.where("A.OperationsStatus IN (2,3)");

		cond.setOrderby("A.Vgsbm asc");
		return commonApiService.searchLay(cond);
	}

	/**
	 * 运营公司弹出框调用
	 */
//	@RequiresPermissions("tpFbaPlanOrder:view")
	@RequestMapping("/searchForBoutique")
    @ResponseBody
	public LayuiTableVoJA searchForBoutique(@ModelAttribute ThrOperateCompanyApply cond){
		
		commonApiService.dataAuth(MenuId.THR_OperateCompanyApply, cond);
		
		cond.addField("(A.VGsBm + '/' + A.VGsMc) AS nameLinked");
		cond.addField("A.Vgsbm AS vGsBm");
		cond.addField("A.Vgsmc AS vGsMc");
		cond.addField("A.Vgsjc AS vGsJc");
		cond.addField("A.Cuser AS cUser");
		
		cond.addLeftJoin("TS_UserChange B on B.Id = A.OperatorChangeId")
			.addField("B.UserId operatorUserId")//运营人工号
			.addField("B.UserName operatorUserName")//运营人
			
			.addField("B.RoleName roleName")//运营人岗位
			.addField("B.RoleName operatorRoleName")//运营人岗位
			
			.addField("B.DeptName deptName");//运营人部门

		cond.where("A.OperationsStatus IN (2,3)");
		//cond.setEffectStock(1);
		cond.setOrderby("A.VGsBm asc");
		return commonApiService.searchLay(cond);
	}
	
	/**
	 * 编辑
	 */
	@RequiresPermissions("thrOperateCompanyApply:edit")
	@PostMapping("/edit")
    @ResponseBody
	public R edit(@RequestParam Map<String, Object> params,
			Long operateOrgId){
		try {
			return thrOperateCompanyApplyService.edit(params);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}


	/**
	 * 运营公司弹出框调用商品备案申请
	 */
	@RequestMapping("/searchForModalSp")
	@ResponseBody
	public LayuiTableVoJA searchForModalSp(@ModelAttribute ThrOperateCompanyApply cond){
		
		cond.addLeftJoin("TS_UserChange B on B.Id = A.OperatorChangeId");
		cond.addField("A.Vgsbm AS vGsBm");
		cond.addField("A.Vgsmc AS vGsMc");
		cond.addField("A.Vgsjc AS vGsJc");
		cond.addField("A.Cuser AS cUser");
		cond.where("A.OperationsStatus IN (2,3)");
		//权限
		cond = commonApiService.dataAuth(MenuId.THR_OperateCompanyApply, cond);

		return commonApiService.searchLay(cond);
	}

	/**
	 * 运营公司弹出框调用运营公司银行账户管理
	 */
	@RequestMapping("/searchForModalYh")
	@ResponseBody
	public LayuiTableVoJA searchForModalYh(@ModelAttribute ThrOperateCompanyApply cond){
		//cond.setEffectStock(1)
		cond.addLeftJoin("TS_OperateOrg C on C.Id = A.OperateOrgId")
		.addLeftJoin("THR_OperateCompanyApply toca ON  toca.vgsbm = A.vgsbm")
		.addField("C.Name operateOrgName")
		.addField("A.vgsbm AS vgsbm,A.vgsjc AS vgsjc");
		cond.where("A.OperationsStatus IN (2,3)");
		cond = commonApiService.dataAuth(MenuId.THR_OperateCompanyBankInfo, cond);
		return commonApiService.searchLay(cond);
	}



    /**
     * 运营公司档案菜单，设置查询的cond的sql设置
     */
    public ThrOperateCompanyApply setSeachSqlByArchives(ThrOperateCompanyApply cond){

        cond.addLeftJoin("TS_UserChange B on B.Id = A.OperatorChangeId")
                .addField("B.UserId operatorUserId")//运营人工号
                .addField("B.UserName operatorUserName")//运营人
                .addField("B.RoleName roleName")//运营人岗位
                .addField("B.DeptName deptName");//运营人部门

		cond.addLeftJoin("TS_OperateOrg O on O.Id = A.OperateOrgId")
				.addField("O.Name orgName");//机构名称

        //cond.addLeftJoin("THR_CanvassApplyItem C on C.Id = A.CanvassApplyItemId AND 1=1")
               // .addField("C.InvestType investType")//招商类型
                //.addField("C.CostStandard costStandard");//费用标准
        /*
        cond.addLeftJoin("TS_UserChange U on U.Id = A.CreateChangeId")
                .addField("U.UserId createUserId")//制单人工号
                .addField("U.UserName createUserName")//制单人
                .addField("U.RoleName createRoleName")//制单人岗位
                .addField("U.DeptName createDeptName");//制单人部门

        cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditTime");//审核时间
         */

        cond.setOrderby("A.Vgsbm desc");
        //权限
        cond = commonApiService.dataAuth(MenuId.THR_OperateCompanyApply_By_Archives, cond);
        return  cond;
    }


    /**
     * 运营公司档案菜单，查询
     */
    @RequestMapping("/searchByArchives")
    @ResponseBody
    public LayuiTableVoJA searchByArchives(@ModelAttribute ThrOperateCompanyApply cond){
        cond = setSeachSqlByArchives(cond);
        return commonApiService.searchLay(cond);
    }


	/**
	 * 运营公司档案菜单，导出
	 */
	@RequestMapping("/exportByArchives")
	@ResponseBody
	public R exportByArchives(@ModelAttribute ThrOperateCompanyApply cond){
		try {
			cond.setPage(0).setSize(999999);
			cond = setSeachSqlByArchives(cond);
			//获取菜单字段数据
			List<YsCol> listField = new YsCol()
					.setMenuId(MenuId.THR_OperateCompanyApply_By_Archives)
					.setFrontShow(1)
					.setOrderby("A.SortNo asc")
					.queryList();
			//获取数据
			List<Map<String, Object>> listData = cond.queryMap();
			//处理数据
			ExportExcelUtils<ThrOperateCompanyApply> util = new ExportExcelUtils<>(new ThrOperateCompanyApply());
			String toFilePath = util.exportExcel(listData, listField, "运营公司档案");
			UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
			return R.ok(dto.getUrl());
		}catch (Exception e){
			logger.error("导出出错：",e.getMessage(),e);
			return R.error("导出失败，请稍后重试！");
		}
	}

	/**
	 * 运营公司档案表-保存
	 */
	public R saveByArchives(Map<String, Object> params,Long menuId , boolean hasSonList ){
		try {
			return thrOperateCompanyApplyService.editByArchives(params, menuId, hasSonList);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}


	/**
	 * 运营维护修改
	 */
	@RequestMapping("/toEditByOperations")
	@ResponseBody
	public R toEditByOperations(@RequestParam Map<String, Object> params){
		return saveByArchives(params,MenuId.THR_OperateCompanyApply_By_Archives_Operations,false);
	}

	/**
	 * 市场维护修改
	 */
	@RequestMapping("/toEditByMarkets")
	@ResponseBody
	public R toEditByMarkets(@RequestParam Map<String, Object> params){
		return saveByArchives(params,MenuId.THR_OperateCompanyApply_By_Archives_Markets,true);
	}

	/**
	 * 管理维护修改
	 */
	@RequestMapping("/toEditByManage")
	@ResponseBody
	public R toEditByManage(@RequestParam Map<String, Object> params){
		return saveByArchives(params,MenuId.THR_OperateCompanyApply_By_Archives_Manage,true);
	}

	/**
	 * 删除列表信息 - 运营公司表VPS信息
	 */
	@RequestMapping("/toDelItemByVps")
	@ResponseBody
	public R toDelItemByVps(@RequestParam("list") List<String> idList){
		try {
			for(int i=0;i<idList.size();i++) {
				thrOperateCompanyVpsService.del(Long.parseLong(idList.get(i)));//删除
			}
			return R.ok();
		}catch (Exception e) {
			logger.error("删除出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 删除列表信息 - 运营公司表品牌信息
	 */
	@RequestMapping("/toDelItemByCompanyBrand")
	@ResponseBody
	public R toDelItemByCompanyBrand(@RequestParam("list") List<String> idList){
		try {
			for(int i=0;i<idList.size();i++) {
				thrOperateCompanyBrandService.del(Long.parseLong(idList.get(i)));//删除
			}
			return R.ok();
		}catch (Exception e) {
			logger.error("删除出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 删除列表信息 - 运营公司表欧洲贸易合规
	 */
	@RequestMapping("/toDelItemByCompanyEuropeTrade")
	@ResponseBody
	public R toDelItemByCompanyEuropeTrade(@RequestParam("list") List<String> idList){
		try {
			for(int i=0;i<idList.size();i++) {
				thrOperateCompanyEuropeTradeService.del(Long.parseLong(idList.get(i)));//删除
			}
			return R.ok();
		}catch (Exception e) {
			logger.error("删除出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}


	/**
	 * 运营公司弹出框调用HW商品选品库
	 */
	@RequestMapping("/searchForModalXp")
	@ResponseBody
	public LayuiTableVoJA searchForModalXp(@ModelAttribute ThrOperateCompanyApply cond){
		cond.addField("A.vgsbm AS vgsbm,A.vgsjc AS vgsjc,A.vgsmc AS vgsmc");
		cond = commonApiService.dataAuth(MenuId.TOS_ProductSelection, cond);
		return commonApiService.searchLay(cond);
	}

	/**
	 * 运营公司(预付款退回调用)
	 */
	@RequestMapping("/searchForTh")
	@ResponseBody
	public LayuiTableVoJA searchForTh(@ModelAttribute ThrOperateCompanyApply cond){

		cond = commonApiService.dataAuth(MenuId.THR_OperateCompanyApply, cond);
		cond.addLeftJoin("TS_UserChange B on B.Id = A.OperatorChangeId")
				.addField("B.UserId operatorUserId")//运营人工号
				.addField("B.UserName operatorUserName")//运营人
				.addField("B.RoleName roleName")//运营人岗位
				.addField("B.DeptName deptName");//运营人部门

		cond.addLeftJoin("TS_OperateOrg O on O.Id = A.OperateOrgId")
				.addField("O.Name orgName");//机构名称
		cond.setOrderby("A.Vgsbm desc");

		cond.addField("case when (SELECT count(1) FROM TCW_OperateCompanyPrepayment wcp WHERE wcp.vgsbm = A.vgsbm AND wcp.operateCompanyPrepaymentType = 0 AND WCP.PreResAmount != 0) > 0 then '是' else '否' end as isDk");
		cond.setOrderby("A.Vgsbm asc");
		return commonApiService.searchLay(cond);
	}
	/**
	 * 运营公司弹出框调用
	 */
//	@RequiresPermissions("tpFbaPlanOrder:view")
	@RequestMapping("/searchForLogistics")
	@ResponseBody
	public LayuiTableVoJA searchForLogistics(@ModelAttribute ThrOperateCompanyApply cond){
		cond.addField("(A.Vgsbm + '/' + A.Vgsjc) AS nameLinked");

		cond.addLeftJoin("TS_UserInfo B on B.UserId = A.CUser")
				.addLeftJoin("YS_Role C on C.Id = B.RoleId")
				.addField("C.Name operatorRoleName");

		cond.addLeftJoin("TS_UserChange D on D.Id = A.OperatorChangeId")
				.addField("D.UserId operatorUserId")
				.addField("D.UserName operatorUserName")
				.addField("D.DeptId operatorDeptId");
		/*
		cond.addField("CASE " +
				"WHEN A.OperationsAttribute=2 THEN '运营账户' " +
				" ELSE '非运营账户' END operationsAttributetxt");//运营属性

		 */
		cond.addLeftJoin("TB_StaticConfig SC ON SC.Lev=A.OperationsAttribute AND SC.KeyTwo = 'OperateCompanyApply-OperationsAttribute' ")
				.addField("SC.Name operationsAttributetxt");//运营属性


		cond.where("A.OperationsStatus IN (2,3)");

		cond.setOrderby("A.Vgsbm asc");
		return commonApiService.searchLay(cond);
	}




	/**
	 * 数据统计店铺清单新增 调用
	 */
//	@RequiresPermissions("tpFbaPlanOrder:view")
	@RequestMapping("/searchForModalByBusinessDataGs")
	@ResponseBody
	public LayuiTableVoJA searchForModalByBusinessDataGs(@ModelAttribute ThrOperateCompanyApply cond){

		//调取未被调用过的
		cond.where("(SELECT count(1) FROM [kjecp_report].[dbo].TCO_BusinessDataGs B WHERE B.Vgsbm = A.Vgsbm) = 0 ");

		cond.where("A.OperationsStatus IN (2,3)");

		cond.setOrderby("A.Vgsbm asc");
		return commonApiService.searchLay(cond);
	}


}
